package android.ijiajiao.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import android.ijiajiao.dao.FriendDao;
import android.ijiajiao.util.JDBCConnectUtil;

public class FriendDaoImpl implements FriendDao {
	/**
	 * 添加好友
	 */
	@Override
	public boolean addFriend(String name, String friend_name) {
		boolean flag = false;
		Connection conn = JDBCConnectUtil.getConnection();
		PreparedStatement ps = null;
		String sql = "insert into friend (name,friend_name) values (?,?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			ps.setString(2, friend_name);
			int row = ps.executeUpdate();
			if (row > 0) {
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCConnectUtil.close(null, null, ps, conn);
		}

		return flag;
	}

	/**
	 * 好友列表
	 */

	@Override
	public ArrayList<Object> friend(String name) {
		Connection conn = JDBCConnectUtil.getConnection();
		PreparedStatement ps = null;
		String sql = "select name,img from user where name in (select friend_name from friend where name = ?) order by name asc";
		ResultSet rs = null;
		ArrayList<Object> data = new ArrayList<>();
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			rs = ps.executeQuery();
			ArrayList<String> list = null;
			while (rs.next()) {
				list = new ArrayList<>();
				list.add(rs.getString(1));
				list.add(rs.getString(2));
				data.add(list);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			JDBCConnectUtil.close(rs, null, ps, conn);
		}
		return data;
	}

	/**
	 * 查找好友
	 */
	@Override
	public ArrayList<Object> findfriend(String name) {
		// TODO Auto-generated method stub
		Connection conn = JDBCConnectUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select img from user where name = ?";
		ArrayList<Object> data = new ArrayList<>();
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			rs = ps.executeQuery();
			while (rs.next()) {
				data.add(name);
				data.add(rs.getString(1));
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCConnectUtil.close(rs, null, ps, conn);

		}
		return data;
	}

}
